<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions" class="is--card">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsDataAll"
          :formData="form"
        >
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-tabs
          v-model="activeName"
          class="w-full h-[40px]"
          @tab-change="handleStatusChange"
        >
          <el-tab-pane
            :label="item.label"
            :name="item.value"
            v-for="item in tabs"
            :key="item.value"
          ></el-tab-pane>
        </el-tabs>
        <VActionBar :actions="actions">
          <template #left>
            <el-select
              v-if="
                activeName === 'HISTORY_4_WEEK' ||
                activeName === 'HISTORY_WEEK' ||
                activeName === 'HISTORY_MONTH'
              "
              v-model="pay_due_date"
              placeholder="请选择历史周期"
              clearable
              @change="handleDueDate"
              style="width: 240px; margin-right: 8px"
            >
              <el-option
                v-for="item in pay_due_date_list"
                :key="item.snapshot_cycle_md5"
                :label="item.show_cycle"
                :value="item.snapshot_cycle_md5"
              />
            </el-select>
          </template>
        </VActionBar>
      </template>
      <template #pay_month="{ row }">
        <div>
          {{ row?.pay_due_date || "-" }}
        </div>
      </template>
      <template #operation="{ row }">
        <el-button
          type="primary"
          link
          @click="handleSubmit(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.submit]"
          >提交</el-button
        >
        <el-button
          type="danger"
          link
          @click="handleDelete(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.delete]"
          >删除</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleEdit(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.Adjust]"
          >调整</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleAudit(row)"
          v-if="row.audit_status == 2"
          v-hasPermi="[financeManageAuthList.fund_plan.audit]"
          >财务确认</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleLog(row)"
          v-hasPermi="[financeManageAuthList.fund_plan.log]"
          >日志</el-button
        >
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      @refresh="query"
      :id="addId"
      :optionsData="optionsDataAll"
      @close="addId = null"
    />
    <ConfirmInput
      title="审核"
      class="w-[500px]"
      confirmButtonText="确认"
      v-model="approvalVisible"
      :loading="loading"
      :field-options="approvalOptions"
      :rules="approvalRules"
      @submit="handleApprovalReq"
    />
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="finance.logistics-fund-plan"
      :business_id="logId"
      @close="logId = null"
    />
    <ImportDialog ref="importDialogRef" @refresh="handleRefresh" />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { columnsData, columnsDataNext, columnsMonth } from "./data.js";
import XForm from "@/components/XForm/index.vue";
import { useEnumSelect } from "@/hooks";
import { logisticsList } from "@/api/index.js";
import {
  snapshotCycle,
  opSure,
  opSubmit,
  lfpDelete,
  opNextWeekList,
  opNextAfter4WeekList,
  opHistoryWeekList,
  opHistory4WeekList,
  opCurrentMonthList,
  opHistoryMonthList,
} from "./api/index.js";
import {
  getNextWeekMonday,
  printFourWeeksDates,
  generateDateRangeArray,
} from "@/utils/index.js";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import Add from "./components/add/index.vue";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
import Log from "@/components/Log/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import ImportDialog from "@/components/importDialog/index.vue";
import { formatTime } from "@/utils/time.js";
import { config_name } from "@/config/export.js";
const { proxy } = getCurrentInstance();
const load = ref(true);
const tableRef = ref();
let tableColumns = JSON.parse(JSON.stringify(columnsData));
let tableColumnsFilter = tableColumns;
const tableOptions = reactive({
  formConfig: {
    data: {},
  },
  border:true,
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: tableColumnsFilter,
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return handleReq({ ...page, ...form });
      },
    },
  },
});
const handleReq = async (val) => {
  try {
    const _api = {
      HISTORY_WEEK: opHistoryWeekList,
      HISTORY_4_WEEK: opHistory4WeekList,
      NEXT_WEEK: opNextWeekList,
      NEXT_AFTER4_WEEK: opNextAfter4WeekList,
      CURRENT_MONTH: opCurrentMonthList,
      HISTORY_MONTH: opHistoryMonthList,
    };
    const res = await _api[activeName.value](val);
    const { total } = res;
    // const data = res?.data || {};
    const data = updataTable(res?.data);
    return { data, total };
  } catch (e) {
    console.error(e);
  }
};
const time_history = ref([]);
const updataTable = (data) => {
  switch (activeName.value) {
    case "HISTORY_4_WEEK":
      data?.forEach((item) => {
        let ind = findNumberInArray(
          item?.expected_pay_date,
          time_history.value
        );
        if (ind) {
          item[`day_${ind[0]}_${ind[1]}`] = item?.amount;
        }
      });
      break;
    case "NEXT_AFTER4_WEEK":
      let day = getNextWeekMonday(2);
      let time = printFourWeeksDates(day);
      data?.forEach((item) => {
        let ind = findNumberInArray(item?.expected_pay_date, time);
        if (ind) {
          item[`day_${ind[0]}_${ind[1]}`] = item?.amount;
        }
      });
      break;
  }
  return data;
};
function findNumberInArray(target, arr) {
  for (let i = 0; i < arr?.length; i++) {
    for (let j = 0; j < arr[i]?.length; j++) {
      if (arr[i][j] === target) {
        return [i, j];
      }
    }
  }
  return null;
}
const { options: optionsData } = useEnumSelect({
  params: [
    "finance_lfp_payment_type",
    "finance_lfp_settle_type",
    "finance_charge_status",
    "finance_lpo_pay_main_company",
    "finance_lfp_snapshot_type",
  ],
});
const optionsData1 = ref({});
//获取物流商
const getlogistics = () => {
  logisticsList({}).then((res) => {
    optionsData1.value.logistics = res?.data || [];
  });
};
getlogistics();
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value)
);

const pay_due_date_list = ref([]);
const pay_due_date = ref(null);
const getSnapshotCycle = async (type) => {
  try {
    let { data } = await snapshotCycle({ snapshot_type: type });
    pay_due_date_list.value = data || [];
    pay_due_date.value = data.length
      ? data[0]?.snapshot_cycle_md5 || null
      : null;
  } catch (error) {
    pay_due_date_list.value = [];
    pay_due_date.value = null;
  }
};

const tabs = computed(() => optionsDataAll.value["finance_lfp_snapshot_type"]);

const activeName = ref("NEXT_WEEK");

const handleStatusChange = async (e) => {
  if (e === "HISTORY_4_WEEK" || e === "HISTORY_WEEK" || e === "HISTORY_MONTH") {
    await getSnapshotCycle(e);
  }
  tableOptions.columns = [];
  let data = getNextWeekMonday(2);
  let time = printFourWeeksDates(data);
  const chineseNumbers = ["一", "二", "三", "四", "五", "六", "日"];
  nextTick(() => {
    switch (e) {
      case "HISTORY_WEEK":
        //将columnsData里面的操作列去掉
        let tableColumns = JSON.parse(JSON.stringify(columnsData));
        tableOptions.columns = tableColumns.filter((item) => {
          return item.field !== "operation";
        });
        break;
      case "HISTORY_4_WEEK":
        // tableOptions.columns = columnsDataNext;
        // tableOptions.columns = columnsDataNext;
        break;
      case "NEXT_WEEK":
        tableOptions.columns = columnsData;
        break;
      case "NEXT_AFTER4_WEEK":
        let arr = [];
        for (let i = 0; i < 4; i++) {
          let obj = {
            title: `后${chineseNumbers[i]}周`,
            children: [],
          };
          for (let j = 0; j < 7; j++) {
            obj.children.push({
              title: `周${chineseNumbers[j]}`,
              children: [
                {
                  field: `day_${i}_${j}`,
                  title: `${time[i][j]}`,
                  width: 110,
                },
              ],
            });
          }
          arr.push(obj);
        }
        tableOptions.columns = [...columnsDataNext, ...arr];
        break;
      case "CURRENT_MONTH":
        tableOptions.columns = columnsMonth;
        break;
      case "HISTORY_MONTH":
        tableOptions.columns = columnsMonth;
        break;
    }
    tableRef.value?.$table.loadColumn(tableOptions.columns);
    tableRef.value.setForm({
      now_date: formatTime(null, "YYYY-MM-DD HH:mm:ss"),
    });
    tableRef.value.query();
  });
};
const dueDate = computed(() => {
  if (pay_due_date.value) {
    let item = pay_due_date_list.value?.find(
      (item) => item.snapshot_cycle_md5 === pay_due_date.value
    );
    return item?.snapshot_cycle || [];
  }
  return [];
});
watch(
  () => dueDate.value,
  (val) => {
    // tableOptions.columns = [];
    time_history.value = [];
    const chineseNumbers = ["一", "二", "三", "四", "五", "六", "日"];
    nextTick(() => {
      if (val?.length && activeName.value == "HISTORY_4_WEEK") {
        let time = generateDateRangeArray(val[0], val[1]);
        time_history.value = time;
        let arr = [];
        for (let i = 0; i < 4; i++) {
          let obj = {
            title: `后${chineseNumbers[i]}周`,
            children: [],
          };
          for (let j = 0; j < 7; j++) {
            obj.children.push({
              title: `周${chineseNumbers[j]}`,
              children: [
                {
                  field: `day_${i}_${j}`,
                  title: `${time[i][j]}`,
                  width: 110,
                },
              ],
            });
          }
          arr.push(obj);
        }
        tableOptions.columns = [...columnsDataNext, ...arr];
      }
      if (!val?.length && activeName.value == "HISTORY_4_WEEK") {
        tableOptions.columns = columnsDataNext;
      }
    });
  }
);
const handleDueDate = (e) => {
  tableRef.value.setForm({
    snapshot_cycle_md5: pay_due_date.value || null,
  });
  tableRef.value.query();
};

const addVisible = ref(false);
const handleAdd = () => {
  addVisible.value = true;
};
const addId = ref(null);
const handleEdit = (row) => {
  addVisible.value = true;
  addId.value = row?.id;
};

const importDialogRef = ref();
const handleImport = () => {
  importDialogRef.value?.open({
    type: "finance.logisticsFundPlan",
    urlType: "/finance/lfp/import",
  });
};
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["lfp"],
    condition,
  });
};

const handleSubmit = (row) => {
  handleSubmitReq(row?.id);
};
const handleBatchSubmit = () => {
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  handleSubmitReq(id);
};
const handleSubmitReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认提交 {id?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await opSubmit({
            id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("提交成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          query();
        }
      } else {
        done();
      }
    },
  });
};

const approvalOptions = [
  {
    label: "审核状态",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    style: { marginTop: "10px" },
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];
const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
const approvalVisible = ref(false);
const loading = ref(false);
const auditData = ref(null);
const handleAudit = (row) => {
  approvalVisible.value = true;
  auditData.value = row?.id;
};
const handleBatchAudit = () => {
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  approvalVisible.value = true;
  auditData.value = id;
};
const handleApprovalReq = async (formValues) => {
  const obj = {
    id: auditData.value,
    ...formValues,
  };
  try {
    loading.value = true;
    const { code, message } = await opSure(obj);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("操作成功");
    auditData.value = null;
    approvalVisible.value = false;
    query();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

const handleBatchDelete = () => {
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  handleDeleteReq(id);
};
const handleDelete = (row) => {
  handleDeleteReq(row?.id);
};
const handleDeleteReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: <p>确认删除 {id?.length || 1} 条数据？</p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await lfpDelete({
            id,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success("删除成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          query();
        }
      } else {
        done();
      }
    },
  });
};

const logVisible = ref(false);
const logId = ref(null);
const handleLog = (item) => {
  logId.value = item?.id;
  logVisible.value = true;
};
const query = () => {
  tableRef?.value.query();
};
const publicStyle = { style: { width: "360px" } };
const fieldList = [
  {
    field: "logistics_id",
    type: "select",
    originOption: "logistics",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
    class: "select-wrapper-style",
    style: { width: "300px" },
  },
  {
    field: "settle_type",
    type: "select",
    originOption: "finance_lfp_settle_type",
    options: {
      placeholder: "结算类型",
    },
    style: { width: "100px" },
  },
  {
    field: "pay_main_company_id",
    type: "select",
    originOption: "finance_lpo_pay_main_company",
    options: {
      placeholder: "付款主体",
    },
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "120px" },
    select: [{ label: "贷款所属期", value: "pay_due_date" }],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];

const actions = ref([
  {
    label: "新增",
    type: "primary",
    fn: handleAdd,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.add],
  },
  {
    label: "批量提交",
    type: "primary",
    fn: handleBatchSubmit,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.submit],
  },
  {
    label: "批量财务确认",
    type: "primary",
    fn: handleBatchAudit,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.audit],
  },
  {
    label: "批量删除",
    fn: handleBatchDelete,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.delete],
  },
  {
    label: "导入",
    right: true,
    fn: handleImport,
    show: () => activeName.value === "NEXT_WEEK",
    permission: [financeManageAuthList.fund_plan.import],
  },
  {
    label: "导出",
    right: true,
    fn: handleExport,
    permission: [financeManageAuthList.fund_plan.export],
  },
]);
</script>
